<?php

namespace humhub\modules\api\controllers;

use Yii;
use humhub\modules\comment\models\Comment;
use yii\web\HttpException;
use humhub\modules\post\models\Post;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 评论的: 获取, 发布, 编辑, 删除
 */
class CommentController extends Base3Controller
{

    /**
     * @inheritdoc
     */
    public function init(){
        $_GET['contentModel'] =  'humhub\modules\post\models\Post';
        $_POST['contentModel'] =  'humhub\modules\post\models\Post';
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        $behaviors['acl'] = [
            'class' => \humhub\components\behaviors\AccessControl::className(),
            'guestAllowedActions' => ['show']
        ];

        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function actions(){
        $actions = parent::actions();
        unset($actions['update'], $actions['create'], $actions['index'], $actions['delete']);
        return $actions;
    }

    /**
     * 获取评论列表
     *
     * GET /api/comment
     *
     * get.contentId 内容ID
     *
     * get.contentModel 固定值=[post]
     *
     * get.uid 用户uid，新增属性，过滤指定用户的列表（用于显示某用户的任务结果列表）
     *
     * @return array 部分属性说明:(message评论内容, user发布评论的用户, created_at评论时间)
     */
    public function actionShow(){
        $content = $this->parentContent;

        //$pagination = new \yii\data\Pagination([
        //    'totalCount' => Comment::GetCommentCount($content->className(), $content->getPrimaryKey()),
        //    'pageSize' => 10, //$this->module->commentsBlockLoadSize
        //]);
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 10,
            'validatePage' => false,
        ]);

        $where = [
            'object_model' => $content->className(),
            'object_id' => $content->getPrimaryKey(),
        ];
        $uid = (int)Yii::$app->request->get('uid');
        if( $uid ){
            $where['created_by'] = $uid;
        }

        $query = Comment::find();
        $query->orderBy('created_at DESC');
        $query->where($where);
        $query->offset($pagination->offset)->limit($pagination->limit);
        //$comments = array_reverse($query->all());
        $comments = $query->all();

        $output = array();
        foreach ($comments as $comment) {
            $user['displayname'] = $comment->user->displayName;
            $user['guid'] = $comment->user->guid;
            $user['image'] = $comment->user->getProfileImage()->getUrl();
            $user['g_name'] = $comment->user->g_name;
            $user['g_url'] = $comment->user->g_url;

            $_cm = $comment->attributes;
            $cm['id'] = $_cm['id'];
            $cm['message'] = $_cm['message'];
            $cm['object_id'] = $_cm['object_id'];
            $cm['created_at'] = $_cm['created_at'];
            $cm['updated_at'] = $_cm['updated_at'];
            $cm['user'] = $user;
            //$cm['canWrite'] = $comment->canWrite();
            //$cm['canDelete'] = $comment->canDelete();
            //Like
            $cm['likecount'] = \humhub\modules\like\models\Like::find()->where(['object_model' => Comment::className(), 'object_id' => $comment->id])->count();
            $likes = \humhub\modules\like\models\Like::GetLikes(Comment::className(), $comment->id);
            $currentUserLiked = false;
            foreach ($likes as $like) {
                if ($like->user->id == Yii::$app->user->id) {
                    $currentUserLiked = true;
                    break;
                }
            }
            $cm['like']  = $currentUserLiked?'unlike':'like';

            //Files
            if ($comment->isNewRecord && $comment->getRelation('content', false) !== null) {
                $files = \humhub\modules\file\models\File::findAll(['guid' => array_map('trim', explode(',', $comment->content->attachFileGuidsAfterSave))]);
            } else {
                $files = \humhub\modules\file\models\File::getFilesOfObject($comment);
            }
            $cm['image'] = [];
            foreach ($files as $file){
                if ($file->getMimeBaseType() == "image"){
                    $cm['image'][] = $file->getPreviewImageUrl(200, 200);
                }
            }
            $cm['files'] = [];
            foreach ($files as $file){
                if ($file->getMimeBaseType() == "image")
                    continue;
                $f['url'] = $file->getUrl();
                $f['name'] = $file->file_name;
                $f['size'] = $file->size; //Yii::$app->formatter->asSize($file->size);
                $cm['files'][] = $f;
            }

            $output[] = $cm;
        }
        return $output;
    }

    /**
     * 发表评论(更新任务的结果！不在！使用此功能)
     *
     * POST /api/comment
     *
     * post.contentId 内容post的id
     *
     * post.contentModel 固定值=[post]
     *
     * post.type （八卦评论值为1，默认不传）
     *
     * post.message  评论内容
     *
     * post.fileList 上传文件，值为文件的guid，每个guid需以逗号[,]开头
     *
     * @return array 评论的id信息
     */
    public function actionCreate(){

        $this->forcePostRequest();

        if (Yii::$app->user->isGuest) {
            throw new HttpException(403, 'Guests can not comment.');
        }
        
        if (!Yii::$app->getModule('comment')->canComment($this->parentContent->content)) {
            throw new HttpException(403, 'You are not allowed to comment.');
        }

        $postid = Yii::$app->request->post('contentId');
        $post = Post::findOne( $postid );
        if( ! $post ){
            throw new HttpException(403, 'You are not allowed to comment.');
        }

        $message = Yii::$app->request->post('message');
        $files = Yii::$app->request->post('fileList');

        if (trim($message) === '' && trim($files) === '') {
            // do not create empty comments
            Yii::$app->params['res-success'] = false;
            return false;
        }

        $comment = new Comment;
        $comment->message = $message;
        $comment->object_model = $this->parentContent->className();
        $comment->object_id = $this->parentContent->getPrimaryKey();
        $comment->save();

        \humhub\modules\file\models\File::attachPrecreated($comment, $files);

        // Reload comment to get populated created_at field
        $comment->refresh();

        if( $comment ){
            return $comment;
        }
        Yii::$app->params['res-success'] = false;
        return false;
    }


    /**
     * 编辑评论
     *
     * PUT /api/comment
     *
     * post.id = 评论的ID
     *
     * post.contentId  所属post的ID
     *
     * post.Comment[message]  新的评论内容
     *
     * @return boolean
     */
    public function actionEdit(){
        $this->loadContentAddon(Comment::className(), Yii::$app->request->post('id'));

        if (!$this->contentAddon->canWrite()) {
            throw new HttpException(403, Yii::t('CommentModule.controllers_CommentController', 'Access denied!'));
        }

        if ($this->contentAddon->load(Yii::$app->request->post()) && $this->contentAddon->validate() && $this->contentAddon->save()) {

            // Reload comment to get populated updated_at field
            $this->contentAddon = Comment::findOne(['id' => $this->contentAddon->id]);

            return true;
            return $this->contentAddon;
        }

        Yii::$app->params['res-success'] = false;
        return false;
    }

    /**
     * 删除评论
     *
     * POST /api/comment/delete
     *
     * post.id = 评论的ID
     *
     * post.contentId  所属post的ID
     */
    public function actionDelete(){
        $_GET['contentId'] = Yii::$app->request->post('contentId');
        $this->forcePostRequest();
        $this->loadContentAddon(Comment::className(), Yii::$app->request->post('id'));

        if ($this->contentAddon->canDelete()) {
            if( $this->contentAddon->delete() ){
                return true;
            }
            Yii::$app->params['res-success'] = false;
            return false;
        } else {
            throw new HttpException(500, Yii::t('CommentModule.controllers_CommentController', 'Insufficent permissions!'));
        }
    }
}
